import os.path
import uuid
from datetime import datetime
from math import sin, asin, cos, radians, sqrt
from geopy.distance import distance



# 给定一个坐标点和半径，输出园的区域
def get_bounds(center_lat, center_lon, radius_meters):
    """Given a point's latitude and longitude, calculate the bounding box
    that is radius_meters away from the given point."""
    radius_km = radius_meters / 1000.0  # Convert meters to kilometers
    point = (center_lat, center_lon)

    # Create points that are radius_km north/south and east/west of original point
    north = distance(kilometers=radius_km).destination(point, bearing=0)
    south = distance(kilometers=radius_km).destination(point, bearing=180)
    east = distance(kilometers=radius_km).destination(point, bearing=90)
    west = distance(kilometers=radius_km).destination(point, bearing=270)

    return {
        'north': north.latitude,
        'south': south.latitude,
        'east': east.longitude,
        'west': west.longitude
    }

# 判断一个目标点是否在园的区域内
def is_within_bounds(target_lat, target_lon, bounds):
    """Check if the target point is within the given bounds."""
    return bounds['south'] <= target_lat <= bounds['north'] and \
        bounds['west'] <= target_lon <= bounds['east']











# 更新覆盖文件
def update_file(file_name, file_content):
    """
        更新文件
    """
    with open(file_name, 'w', encoding="utf-8") as f:
        f.write(file_content)


def calculate_acceleration(initial_velocity, final_velocity, displacement):
    """
        计算加速度
    """
    acceleration = (final_velocity ** 2 - initial_velocity ** 2) / (2 * displacement)
    return acceleration


# 判断两个点经纬度距离单位 m
def calculate_distance(lon, lat, lon2, lat2):
    """
        计算两个点经纬度距离单位 m
    """
    lng1, lat1, lng2, lat2 = map(radians, [lon, lat, lon2, lat2])  # 经纬度转换成弧度
    dlon = lng2 - lng1
    dlat = lat2 - lat1
    a = sin(dlat / 2) ** 2 + cos(lat1) * cos(lat2) * sin(dlon / 2) ** 2
    distance = 2 * asin(sqrt(a)) * 6371.393 * 1000  # 地球平均半径，6371.393km
    return distance


def calc_time_to_reach(target_speed, target_distance, current_speed, current_acceleration):
    """
        计算到达目标速度所需时间
    """
    v = float(target_speed)
    d = float(target_distance)
    v0 = float(current_speed)
    a = float(current_acceleration)
    t = (v - v0) / a + (d - (v ** 2 - v0 ** 2) / (2 * a)) / v
    return t


def random_file_option(file_path, start_index, end_index, out_path):
    out_file_name = uuid.uuid4()
    out_dir = os.path.join(out_path, "tmp")
    if not os.path.exists(out_dir):
        os.makedirs(out_dir)
    out_file = os.path.join(out_dir, str(out_file_name) + ".txt")
    for index in range(start_index, end_index + 1):
        file_path_index = os.path.join(file_path, str(index) + ".json")
        if os.path.exists(file_path_index):
            # 打开源文件进行读取
            with open(file_path_index, 'r', encoding='utf-8') as file:
                # 读取源文件的全部内容
                content = file.read()
            # 打开目标文件进行写入操作（如果不存在则会自动创建）
            with open(out_file, 'a', encoding='utf-8') as file:
                # 将源文件的内容逐行追加写入到目标文件中
                file.write(content)
    return out_file


def timestamp_to_milliseconds(timestamp_str):
    # 假设时间戳格式为 YYYY.MM.DD-HH.MM.SS.fff
    dt_obj = datetime.strptime(timestamp_str, "%Y.%m.%d-%H.%M:%S:%f")
    return round(dt_obj.timestamp() * 1000)

